import { useEffect, useState,useRef,useMemo } from "react";
import axios from "axios";
const Cate = () => {
    const [data, setData] = useState([]);
    const [height, setheight] = useState(100)
  //单个元素高度
  const [onHeight, setonHeight] = useState(25)
  //最大容积
  const [maxHeight, setmaxHeight] = useState(0)
  //滚动事件
  const scrollshu = useRef(null)
  const [start, setStart] = useState(0);
  //滚动的结束位置
  const [end, setEnd] = useState(0);
  const handleScroll = () => {
    console.log('滚动距离顶的', scrollshu.current.scrollTop);
    setStart(~~(scrollshu.current.scrollTop / onHeight));
  }
    const show=()=>{
       axios.get("http://localhost:3000/ljy/cate").then(res=>{
          console.log(res.data);
          setData(res.data)
       })
    }
    useEffect(()=>{
        setmaxHeight(~~(height / onHeight))
    setStart()
        show()
    },[])
      //上空白
  const shang = useMemo(() => {
    return start * onHeight
  },)
  //下空白
  const xia = useMemo(() => {
    return (data.length - end) * onHeight
  })
    const endIndex = useMemo(() => {
        //开始位置+最大容积数量
        let endindex = start + maxHeight;
        //如果最后一个元素不存在
        // if (!data[endindex]) {
        //   endindex = data.length - 1
        // }
        return endindex
      })
      const showList = useMemo(() => {
        console.log('showList', data);
        return data.slice(start, endIndex)
      })
    return(
        <div>
          <div>
            <div style={{marginLeft:"10rem"}}>商品分类</div>
          <div className='' onScroll={handleScroll} ref={scrollshu}>
              <div style={{ paddingTop: shang + 'px', paddingBottom: xia + 'px' }}>
                <table className='table1' >
                  <tr style={{ fontSize: '0.5rem' }}>
                    <td>序号</td>
                    <td>分类名称</td>
                    <td>图标</td>
                    <td>商品数量</td>
                  </tr>
                  {
                    data.map((item) => {
                      return <tr className='div1'>
                        <td>{item._id}</td>
                        <td>{item.title}</td>
                        <td><img src={item.img} alt="" /><span style={{ position: 'relative', bottom: '1rem', left: '0.5rem' }}></span></td>
                        <td>{item.list?.length}</td>
                        </tr>
                    })
                  }
                </table>
              </div>
            </div>
          </div>
        </div>
    )
}
export default Cate;